function loadAvatarData() {
    // 请求头像数据
    $.ajax({
        url: "http://localhost:8080/people/avatarList",
        method: "GET",
        dataType: "json",
        success: function(response) {
            let avatars = response.data;
            let avatarsTbody = $("#avatars-tbody");
            avatarsTbody.empty();

            avatars.forEach(function(avatar) {
                let avatarURL = avatar.avatar ? '.' + avatar.avatar : './avatars/default_avatar.png';
                console.log(avatarURL);
                avatarsTbody.append(`
        <tr>
            <td>${avatar.id}</td>
            <td>${avatar.name}</td>
            <td><img src="${avatarURL}" alt="${avatar.name}的照片" width="200" height="150"></td>
            <td>
                <button data-toggle="modal" data-target="#add-avatar-modal" data-student-id="${avatar.id}" class="btn btn-primary btn-upload-avatar">上传头像</button>
            </td>
        </tr>
    `);
            });
        },
        error: function(error) {
            console.error("加载头像数据失败：", error);
        }
    });


}

function initializeAvatarTable(){
    loadAvatarData();
    $('#add-avatar-modal').on('show.bs.modal', function (event) {
        let button = $(event.relatedTarget); // Button that triggered the modal
        let studentId = button.data('student-id'); // Extract student ID from data-* attribute
        let modal = $(this);

        modal.find('#student-id-input').val(studentId);

        // 绑定 submit-avatar-btn 点击事件
        $('#submit-avatar-btn').off('click').on('click', function() {
            uploadAvatar(studentId);
        });
    });
    function uploadAvatar(studentId) {
        let formData = new FormData($('#upload-avatar-form')[0]);
        $.ajax({
            url: `http://localhost:8080/people/uploadAvatar/${studentId}`,
            method: "POST",
            data: formData,
            processData: false,
            contentType: false,
            success: function() {
                alert("头像上传成功");
                $('#add-avatar-modal').modal('hide');
                loadAvatarData(); // 重新加载头像数据
            },
            error: function(error) {
                console.error("头像上传失败：", error);
                alert("头像上传失败");
            }
        });
    }

}


function bindAvatarTableEvents(){
    initializeAvatarTable();
}